﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Write.Application.Command.PhysicalGrid;
using SC.GridManage.Domain.Models;
using Yitter.IdGenerator;

namespace SC.GridManage.API.Write.Application.Handler.PhysicalGrid
{
    public class CreatePhysicalHandler : IRequestHandler<CreatePhysicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicalGridModel> physicalGridRepo;
        private readonly ILogger<CreatePhysicalHandler> logger;
        private readonly IMapper mapper;

        public CreatePhysicalHandler(IBaseRepository<PhysicalGridModel> physicalGridRepo,
            ILogger<CreatePhysicalHandler> logger,
            IMapper mapper)
        {
            this.physicalGridRepo = physicalGridRepo;
            this.logger = logger;
            this.mapper = mapper;
        }
        /// <summary>
        /// 中介者添加物理网格的处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(CreatePhysicalGridCommand request, CancellationToken cancellationToken)
        {
            //定义一个ApiResult  公共响应类
            ApiResult<int> result = new ApiResult<int>();

            var physical = mapper.Map<PhysicalGridModel>(request);//把物理网格添加请求参数转换为 Model


           

            //判断网格编号是否已存在
            var count = physicalGridRepo.QueryAsync().Result.Where(x => x.GridNo == request.GridNo).Count();
            if (count > 0)
            { //通过GridNo能查出来数据的物理网格数量大于0 ,说明数据库至少存在一条
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "网格编号已存在.";
                //把result 返回给控制器(调用方)
                return Task.FromResult(result);
            }

            //还要判断同一个区域里,是否已经有了网格
            var girdCount = physicalGridRepo.QueryAsync().Result.Where(x => x.AreaId == request.AreaId).Count();
            if (girdCount > 0)
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Error;
                result.Msg = "同一个区域只能创建一个网格.";
                //把result 返回给控制器(调用方)
                return Task.FromResult(result);
            }

            physical.Id = YitIdHelper.NextId();//使用雪花id给物理网格的id赋值
            int r = physicalGridRepo.CreateAsync(physical).Result;//调用仓储的添加方法

            if (r > 0)//判断受影响的行数是否大于0
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
                result.Msg = "添加成功.";
                result.Data = r;
            }
            else {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "添加失败.";
            }
            //把 公共响应类result 返回给控制器(调用方)
            return Task.FromResult(result);
        }
    }
}
